package com.tourism.www.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tourism.www.common.result.ResultInfo;
import com.tourism.www.entity.UserInfo;
import com.tourism.www.mapper.UserInfoMapper;
import com.tourism.www.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
@Slf4j
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Override
    public ResultInfo<String> register(UserInfo userInfo) {
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getUsername, userInfo.getUsername())
                .or()
                .eq(UserInfo::getMail, userInfo.getMail());
        List<UserInfo> userInfos = this.list(wrapper);

        if (!ObjectUtils.isEmpty(userInfos)) {
            return ResultInfo.error("用户名或邮箱已存在!");
        }

        return ResultInfo.status(this.save(userInfo));
    }


    @Override
    public ResultInfo<String> login(String username, String password) {
        UserInfo userInfo = getUserInfoByUsername(username);

        if (ObjectUtils.isEmpty(userInfo)) {
            return ResultInfo.error("用户名或密码错误!");
        }
        if (!password.equals(userInfo.getPassword())) {
            return ResultInfo.error("用户名或密码错误!");
        }

        return ResultInfo.success(JSONObject.toJSONString(userInfo));
    }

    @Override
    public ResultInfo<String> updatePassword(String username, String newPwd, String oldPwd) {
        UserInfo userInfo = getUserInfoByUsername(username);

        if (ObjectUtils.isEmpty(userInfo)) {
            return ResultInfo.error("用户名或密码错误!");
        }
        if (!oldPwd.equals(userInfo.getPassword())) {
            return ResultInfo.error("用户名或密码错误!");
        }
        UserInfo userInfo1 = JSONObject.parseObject("a", UserInfo.class);
        userInfo.setPassword(newPwd);
        return ResultInfo.status(this.updateById(userInfo));
    }


    private UserInfo getUserInfoByUsername(String username) {
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getUsername, username);
        return this.getOne(wrapper);
    }
}
